package com.hhu.wangzb.shiro.util;

import com.hhu.wangzb.common.security.AuthenticationInfo;
import com.hhu.wangzb.common.security.constant.SecurityConstants;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

public class AuthenticationUtils {

    /**
     * 留存登陆状态
     */
    public static void setAuthenticationInfo(AuthenticationInfo authenticationInfo) {

        Subject subject = SecurityUtils.getSubject();

        subject.getSession().setAttribute(SecurityConstants.S_SESSION_AUTHENTICATION_INFO, authenticationInfo);
    }

    /**
     * 获取登陆状态信息
     */
    public static AuthenticationInfo getAuthenticationInfo() {

        Subject subject = SecurityUtils.getSubject();

        return (AuthenticationInfo) subject.getSession().getAttribute(SecurityConstants.S_SESSION_AUTHENTICATION_INFO);
    }

    /**
     * 登陆失效
     */
    public static void invalidate() {
        Subject subject = SecurityUtils.getSubject();

        subject.getSession().stop();
    }

    /**
     * 是否认证，即判断subject是否留存认证信息
     * @return 是否认证
     */
    public static boolean isAuthenticated() {

        AuthenticationInfo authenticationInfo = getAuthenticationInfo();

        return authenticationInfo != null
                && authenticationInfo.getUserIdInSession() != null
                && authenticationInfo.getUserRoleInSession() != null
                && authenticationInfo.getUserPermissionsInSession() != null;
    }

}
